A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts.
The various ways in which we can initialize a Counter
:
In [ ]:
from collections import Counter
c = Counter() # a new, empty counter
print(c)
In [ ]:
c = Counter('gallahad') # a new counter from an iterable
print(c)
In [ ]:
c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
print(c)
In [ ]:
c = Counter(cats=4, dogs=8) # a new counter from keyword args
print(c)
Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a KeyError:
In [ ]:
c = Counter(['eggs', 'ham'])
c['bacon']
To remove an element from the Counter use del
In [ ]:
del c['eggs']
print(c)
Various mathematical operations can be done on Counters:
In [ ]:
c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c + d # add two counters together: c[x] + d[x]
In [ ]:
c - d # subtract (keeping only positive counts)
In [ ]:
c & d # intersection: min(c[x], d[x])
In [ ]:
c | d # union: max(c[x], d[x])
What does this do?
In [ ]:
c += Counter()